#!/usr/bin/env bash

set -eu

source $SNAP/actions/common/utils.sh

use_snap_env

if [ -e ${SNAP_DATA}/var/lock/clustered.lock ]
then
  echo "api service kicker will not run on a cluster node"
  exit 0
fi

if [ -e "${SNAP_DATA}/var/lock/low-memory-guard.lock" ]
then
	echo "not starting api service kicker because of low memory guard lock"
	exit 0
fi

group=$(get_microk8s_or_cis_group)
restart_attempt=0
installed_registry_help=0

while true
do
    if [ $restart_attempt -ge 5 ]
    then
        echo "Service kicker restarted the apiserver too quickly. Exiting."
        exit 1
    fi

    # every 5 seconds
    sleep 5
    if [ -e "${SNAP_DATA}/var/lock/ha-cluster" ] &&
      [ ! -e "${SNAP_DATA}/var/lock/cis-hardening" ] &&
      getent group ${group} >/dev/null 2>&1
    then
      chmod -R ug+rwX ${SNAP_DATA}/var/kubernetes/backend || true
      chgrp ${group} -R ${SNAP_DATA}/var/kubernetes/backend || true
      chgrp ${group} ${SNAP_COMMON}/run/containerd.sock || true
    fi

    # certificate regeneration on: IP/csr change if not clustered, CA mismatch if clustered
    manage_certs() {
      if ! [ -e "${SNAP_DATA}/var/lock/no-cert-reissue" ] &&
        ! grep -E "(--advertise-address|--bind-address)" $SNAP_DATA/args/kube-apiserver &> /dev/null &&
        ip route | grep default &> /dev/null
      then
        echo "$(produce_certs)"
      else
        echo "$(ensure_server_ca)"
      fi
    }

    if snapctl services microk8s.daemon-kubelite | grep active &> /dev/null
    then
      certs_modified="$(manage_certs)"
      if [[ "$certs_modified" -eq "1" ]] &&
        ! [ -e "${SNAP_DATA}/var/lock/join-in-progress" ]
      then
        echo "cert change detected. Restarting the cluster-agent"
        snapctl restart microk8s.daemon-cluster-agent

        echo "cert change detected. Reconfiguring the kube-apiserver"
        rm -rf .srl
        snapctl stop microk8s.daemon-kubelite
        remove_all_containers
        kill_all_container_shims
        snapctl restart microk8s.daemon-containerd
        snapctl start microk8s.daemon-kubelite
        start_all_containers
        restart_attempt=$[$restart_attempt+1]
      else
        restart_attempt=0
      fi
    fi

    # Run reconcile hooks
    $SNAP/usr/bin/python3 $SNAP/scripts/run-lifecycle-hooks.py reconcile || true

    # If no local-registry-hosting documentation has been installed,
    # install a help guide that points to the microk8s registry docs.
    #
    # Wait until the apiserver is up and is successfully responding to
    # namespace checks before we check for the registry configmap.
    if snapctl services microk8s.daemon-kubelite | grep active &> /dev/null
    then
      if [ $installed_registry_help -eq 0 ] &&
         "$SNAP/kubectl" "--kubeconfig=$SNAP_DATA/credentials/client.config" get namespace kube-public &> /dev/null
      then
        if ! "$SNAP/kubectl" "--kubeconfig=$SNAP_DATA/credentials/client.config" get configmap local-registry-hosting -n kube-public &> /dev/null
        then
          use_manifest registry/registry-help apply
        fi

        installed_registry_help=1
      fi
    fi
done
